package com.seafwg;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;

import static java.util.concurrent.Executors.*;

/**
 * @Author seafwg
 * @Date 2022/7/28 10:42
 * @Version 1.0
 * @Description 创建线程方法四：使用线程池 jdk 5.0
 *  jdk5.0提供类线程池相关的API：ExecutorService和Executors工具类
 *
 * 使用流程：
 *  1.使用Executors工具类的静态方法创建线程池并可以制定线程池的数量
 *  2.通过向上转型转换为ThreadPoolExecutor，可以设置线程的属性
 *  3.通过线程池调用方法execute[适用于实现Runnable接口的线程]/submit[适用于实现了Callable接口的线程]
 *      执行制定的线程
 *  4.关闭连接池
 */

public class ThreadPoolTest {
    public static void main(String[] args) {
        // ExecutorService service = newFixedThreadPool(10);
        // ThreadPoolExecutor threadService = (ThreadPoolExecutor) service;
        ThreadPoolExecutor service = (ThreadPoolExecutor) newFixedThreadPool(10);

        // 执行线程
        service.submit(new MyDemoThread());
        // 关闭线程
        service.shutdown();
    }
}

class MyDemoThread implements Callable {

    @Override
    public Object call() throws Exception {
        int num = 0;
        for (int i = 0; i < 101; i++) {
            if (i % 2 == 0) {
                System.out.println(i);
                num += i;
            }
        }
        return num;
    }
}